import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { CheckOutlined, CloseOutlined, DisconnectOutlined, DownloadOutlined } from "@ant-design/icons";
import { useRequest } from "ahooks";
import type { TableColumnsType, TableProps } from "antd";
import { Avatar, Button, Col, Flex, Image, Row, Tag, Tooltip } from "antd";
import SearchForm from "@/components/search-form";
import Table from "@/components/table";
import BindModal from "./components/bind-modal";
import PassModal from "./components/pass-modal";
import RejectModal from "./components/reject-modal";
import { unbindUserAccount, updateUserAccountStatus, useUserAccountList } from "@/api";
import { ACCOUNT_REVIEW_STATUS_OPTIONS, PLATFORM_OPTIONS } from "@/constants/options";
import { useUserManagerStore } from "@/stores/modules/userManager";
import { dateFormat } from "@/utils/date";

import { UserAccountDataType, UserAccountStatusType } from "@/types/user";

type TableRowSelection<T extends object = object> = TableProps<T>["rowSelection"];

const schema = [
  { name: "nickname", label: "用户呢称", type: "input" },
  {
    name: "status",
    label: "审核状态",
    type: "select",
    componentProps: {
      options: ACCOUNT_REVIEW_STATUS_OPTIONS,
    },
  },
];

const DescriptionItem = ({ title, content }: { title: string; content: React.ReactNode }) => (
  <div className="flex items-center gap-2 w-full h-full mb-4">
    <p className="text-sm text-gray-500 flex-shrink-0 font-bold">{title}:</p>
    <p className="text-sm text-gray-500">{content}</p>
  </div>
);

export default function Account() {
  const { id: userId } = useParams();
  const { data, loading: isFetching, runAsync: fetchList, refresh } = useUserAccountList();
  const currentUserDetail = useUserManagerStore((state) => state.currentUserDetail);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRecords, setSelectedRecords] = useState<UserAccountDataType[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: data?.length,
  });
  const [queryParams, setQueryParams] = useState({
    page: 1,
    pageSize: 10,
    userId: Number(userId || 0),
  });

  // Modal状态
  const [openRejectModal, setOpenRejectModal] = useState(false);
  const [openBindModal, setOpenBindModal] = useState(false);
  const [openPassModal, setOpenPassModal] = useState(false);
  const [currentActionData, setCurrentActionData] = useState<
    UserAccountDataType | UserAccountDataType[] | null
  >(null);
  const [batchLoading, setBatchLoading] = useState(false);

  // 统一的状态更新API
  const { run: runUpdateStatus, loading: isUpdating } = useRequest(
    async (data: { id: number; userId: number; status: UserAccountStatusType; reason?: string }) =>
      updateUserAccountStatus(data),
    { manual: true },
  );

  // 解绑API
  const { run: runUnbind, loading: isUnbinding } = useRequest(
    async (data: { id: number; userId: number }) => unbindUserAccount(data),
    {
      manual: true,
      onSuccess: () => {
        window.$message?.success("解绑成功");
        refresh();
      },
      onError: () => {
        window.$message?.error("解绑失败");
      },
    },
  );

  // 检查选中项的状态一致性
  const checkStatusConsistency = (records: UserAccountDataType[]) => {
    if (records.length === 0) return { isConsistent: false, status: null };
    const firstStatus = records[0].status;
    const isConsistent = records.every((record) => record.status === firstStatus);
    return { isConsistent, status: firstStatus };
  };

  // 批量通过处理
  const handleBatchPass = () => {
    if (selectedRecords.length === 0) {
      window.$message?.warning("请选择要操作的账号");
      return;
    }

    const { isConsistent, status } = checkStatusConsistency(selectedRecords);

    if (!isConsistent) {
      window.$message?.warning("选择的账号状态包含多个绑定状态，需一致哦");
      return;
    }

    switch (status) {
      case "verified":
        window.$message?.info("账号已审核通过");
        break;
      case "denied":
      case "pending":
        // 已驳回或待审核 -> 都需要二次确认弹窗
        setCurrentActionData(selectedRecords);
        setOpenPassModal(true);
        break;
    }
  };

  // 批量驳回处理
  const handleBatchReject = () => {
    if (selectedRecords.length === 0) {
      window.$message?.warning("请选择要操作的账号");
      return;
    }
    const { isConsistent, status } = checkStatusConsistency(selectedRecords);
    if (!isConsistent) {
      window.$message?.warning("选择的账号状态包含多个绑定状态，需一致哦");
      return;
    }
    switch (status) {
      case "denied":
        window.$message?.info("账号已驳回");
        break;
      case "pending":
      case "verified":
        // 待审核或已通过 -> 弹窗填写驳回原因
        setCurrentActionData(selectedRecords);
        setOpenRejectModal(true);
        break;
    }
  };

  // 单个通过处理
  const handleSinglePass = (record: UserAccountDataType) => {
    switch (record.status) {
      case "verified":
        window.$message?.info("账号已审核通过");
        break;
      case "denied":
      case "pending":
        // 已驳回或待审核 -> 二次确认弹窗
        setCurrentActionData(record);
        setOpenPassModal(true);
        break;
    }
  };

  // 单个驳回处理
  const handleSingleReject = (record: UserAccountDataType) => {
    switch (record.status) {
      case "denied":
        window.$message?.info("账号已驳回");
        break;
      case "pending":
      case "verified":
        // 待审核或已通过 -> 弹窗填写驳回原因
        setCurrentActionData(record);
        setOpenRejectModal(true);
        break;
    }
  };

  // 执行单个状态更新
  const handleSingleUpdate = async (
    record: UserAccountDataType,
    status: UserAccountStatusType,
    reason?: string,
  ) => {
    try {
      await runUpdateStatus({
        id: record.id,
        userId: Number(userId || 0),
        status,
        ...(reason && { reason }),
      });
      window.$message?.success(status === "verified" ? "审核通过成功" : "驳回成功");
      refresh();
    } catch {
      window.$message?.error("操作失败");
    }
  };

  // 执行批量状态更新
  const handleBatchUpdate = async (
    records: UserAccountDataType[],
    status: UserAccountStatusType,
    reason?: string,
  ) => {
    setBatchLoading(true);
    try {
      const results = await Promise.allSettled(
        records.map((record) =>
          updateUserAccountStatus({
            id: record.id,
            userId: Number(userId || 0),
            status,
            ...(reason && { reason }),
          }),
        ),
      );
      const successCount = results.filter((result) => result.status === "fulfilled").length;
      const failCount = results.length - successCount;
      if (failCount === 0) {
        window.$message?.success(status === "verified" ? "批量审核通过成功" : "批量驳回成功");
        setSelectedRowKeys([]); // 清空选择
        setSelectedRecords([]);
      } else {
        window.$message?.error(`操作完成，成功${successCount}条，失败${failCount}条`);
      }
      refresh();
    } catch {
      window.$message?.error("批量操作失败");
    } finally {
      setBatchLoading(false);
    }
  };

  // Modal确认处理 - 通过
  const handlePassConfirm = () => {
    if (!currentActionData) return;
    if (Array.isArray(currentActionData)) {
      // 批量处理
      handleBatchUpdate(currentActionData, "verified");
    } else {
      // 单个处理
      handleSingleUpdate(currentActionData, "verified");
    }
    setOpenPassModal(false);
    setCurrentActionData(null);
  };

  // Modal确认处理 - 驳回
  const handleRejectConfirm = (reason: string) => {
    if (!currentActionData || !reason.trim()) {
      window.$message?.warning("请填写驳回原因");
      return;
    }
    if (Array.isArray(currentActionData)) {
      // 批量处理
      handleBatchUpdate(currentActionData, "denied", reason);
    } else {
      // 单个处理
      handleSingleUpdate(currentActionData, "denied", reason);
    }
    setOpenRejectModal(false);
    setCurrentActionData(null);
  };

  // 处理解绑按钮点击
  const handleUnbind = (record: UserAccountDataType) => {
    setCurrentActionData(record);
    setOpenBindModal(true);
  };

  // 确认解绑
  const handleUnbindConfirm = () => {
    if (!currentActionData || Array.isArray(currentActionData)) {
      return;
    }
    runUnbind({
      id: currentActionData.id,
      userId: Number(userId || 0),
    });
    setOpenBindModal(false);
    setCurrentActionData(null);
  };

  const onSearch = (values: any) => {
    const newParams = {
      ...values,
      pageNum: 1,
      pageSize: pagination.pageSize,
      userId: Number(userId || 0),
    };
    setQueryParams(newParams);
    setPagination({ ...pagination, current: 1 });
    fetchList(newParams);
  };

  const onPageChange = (page: number, pageSize: number) => {
    const newParams = {
      ...queryParams,
      pageNum: page,
      pageSize: pageSize,
      userId: Number(userId || 0),
    };
    setQueryParams(newParams);
    setPagination({
      ...pagination,
      current: page,
      pageSize: pageSize,
    });
    fetchList(newParams);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    // 获取选中的完整记录
    const selectedRecords =
      data?.items?.filter((item: UserAccountDataType) => newSelectedRowKeys.includes(item.id)) || [];
    setSelectedRecords(selectedRecords);
  };

  const rowSelection: TableRowSelection<UserAccountDataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  useEffect(() => {
    fetchList(queryParams);
  }, [userId]);

  const columns: TableColumnsType<UserAccountDataType> = [
    { title: "用户ID", dataIndex: "id", key: "id", width: 100 },
    {
      title: "账户平台",
      dataIndex: "platform",
      key: "platform",
      width: 150,
      render: (_, record) => PLATFORM_OPTIONS.find((opt) => opt.value === record.platform)?.label,
    },
    { title: "账户昵称", dataIndex: "nickname", key: "nickname", width: 150 },
    {
      title: "帐号头像",
      dataIndex: "avatar",
      key: "avatar",
      width: 150,
      render: (_, record) => (
        <>
          <Avatar src={record.avatar} />
        </>
      ),
    },
    {
      title: "小红书主页",
      dataIndex: "homepage",
      key: "homepage",
      width: 150,
      render: (_, record) => (
        <a href={record.homepage} target="_blank" rel="noopener noreferrer">
          {record.homepage}
        </a>
      ),
    },
    {
      title: "主页图片",
      dataIndex: "homepageImage",
      key: "homepageImage",
      width: 150,
      render: (_, record) => <Image src={record.qrcode} width={100} height={100} />,
    },
    { title: "蒲公英链接", dataIndex: "homepage", key: "homepage", width: 150, render: () => "-" },
    {
      title: "绑定审核状态",
      dataIndex: "status",
      key: "reviewStatus",
      width: 150,
      render: (status: string) => {
        const option = ACCOUNT_REVIEW_STATUS_OPTIONS.find((opt) => opt.value === status);
        if (!option) return <Tag color="default">待审核</Tag>;
        const { label, value } = option;
        return (
          <Tag color={value === "verified" ? "green" : value === "denied" ? "red" : "default"}>{label}</Tag>
        );
      },
    },
    { title: "驳回原因", dataIndex: "reason", key: "reason", width: 150 },
    {
      title: "绑定时间",
      dataIndex: "createdAt",
      key: "createdAt",
      width: 150,
      render: (_, record) => dateFormat(record.createdAt, "YYYY-MM-DD HH:mm:ss"),
    },
    { title: "已报名任务", dataIndex: "registeredTask", key: "registeredTask", render: () => "-" },
    { title: "进行中任务", dataIndex: "inProgressTask", key: "inProgressTask", render: () => "-" },
    { title: "已取消任务", dataIndex: "canceledTask", key: "canceledTask", render: () => "-" },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      width: 150,
      fixed: "right",
      render: (_, record) => (
        <Flex gap={8}>
          <Tooltip title="通过">
            <Button
              type="primary"
              size="small"
              ghost
              className="p-0"
              icon={<CheckOutlined />}
              loading={isUpdating && !batchLoading}
              onClick={() => handleSinglePass(record)}
            />
          </Tooltip>
          <Tooltip title="驳回">
            <Button
              type="primary"
              size="small"
              ghost
              className="p-0"
              icon={<CloseOutlined />}
              loading={isUpdating && !batchLoading}
              onClick={() => handleSingleReject(record)}
            />
          </Tooltip>
          <Tooltip title="解绑">
            <Button
              type="primary"
              size="small"
              ghost
              className="p-0"
              icon={<DisconnectOutlined />}
              loading={isUnbinding}
              onClick={() => handleUnbind(record)}
            />
          </Tooltip>
        </Flex>
      ),
    },
  ];

  const leftActions = (
    <>
      <Button
        disabled={selectedRowKeys.length === 0}
        type="primary"
        size="middle"
        icon={<CheckOutlined />}
        loading={batchLoading}
        onClick={handleBatchPass}
      >
        通过
      </Button>
      <Button
        disabled={selectedRowKeys.length === 0}
        type="primary"
        size="middle"
        ghost
        icon={<CloseOutlined />}
        loading={batchLoading}
        onClick={handleBatchReject}
      >
        驳回
      </Button>
      <Button type="primary" size="middle" ghost icon={<DownloadOutlined />}>
        导出
      </Button>
    </>
  );

  return (
    <>
      <div className="mb-4 bg-white rounded-lg p-4 dark:bg-[#1f1f1f]">
        <Row>
          <Col span={6}>
            <DescriptionItem title="用户呢称" content={currentUserDetail?.nickname || "-"} />
          </Col>
          <Col span={6}>
            <DescriptionItem title="手机号" content={currentUserDetail?.mobile || "-"} />
          </Col>
          <Col span={6}>
            <DescriptionItem title="绑定账号" content={currentUserDetail?.userAccountCount || 0} />
          </Col>
          <Col span={6}>
            <DescriptionItem title="待审核" content={currentUserDetail?.userAccountPendingCount || 0} />
          </Col>
        </Row>
      </div>
      <div className="bg-white rounded-lg p-4 dark:bg-[#1f1f1f]">
        <SearchForm schema={schema} onSearch={onSearch} />
        <Table
          columns={columns}
          dataSource={data?.items}
          loading={isFetching}
          rowKey="id"
          pagination={{ ...pagination, total: Number(data?.total || 0) }}
          rowSelection={rowSelection}
          leftActions={leftActions}
          onPageChange={onPageChange}
        />
      </div>

      <PassModal
        data={currentActionData}
        open={openPassModal}
        onCancel={() => {
          setOpenPassModal(false);
          setCurrentActionData(null);
        }}
        onOk={handlePassConfirm}
      />

      <RejectModal
        data={currentActionData}
        open={openRejectModal}
        onCancel={() => {
          setOpenRejectModal(false);
          setCurrentActionData(null);
        }}
        onOk={handleRejectConfirm}
      />

      <BindModal
        data={currentActionData as UserAccountDataType}
        open={openBindModal}
        loading={isUnbinding}
        onCancel={() => {
          setOpenBindModal(false);
          setCurrentActionData(null);
        }}
        onOk={handleUnbindConfirm}
      />
    </>
  );
}
